<template>
	<view class="main">
		<view class="input_view">
			<input placeholder="请输入手机号" class="input" maxlength="11" type="number" :value="phone" @input="getInput" />
			<text @tap="bindGetCode" :class="checkPhone(true) ? 'active' : ''">{{ num == 60 ? '获取验证码' : '重发' + num + 's' }}</text>
		</view>
		<view class="input_view"><input placeholder="请输入验证码" class="input" type="number" v-model="checkNum" @focus="codeErr = false" /></view>
		<text :class="['red', codeErr ? '' : 'v-h']">验证码输入错误</text>
		<view @tap="bindLoading" :class="['btn', checkPhone() ? 'active' : '']">登录</view>
	</view>
</template>

<script>
import API from '@/static/api/index.js';
import { commonMixinFun } from '@/static/mixins/common.js';
import REG from '@/static/uitls/reg.js';
let setInt = null;
const app = getApp();
export default {
	mixins: [commonMixinFun],
	data() {
		return {
			num: 60,
			phone: '',
			checkNum: '',
			getCode: false,
			getCodeNum: 3,
			codeErr: false,
			destroyMin: 10 // 页面销毁时如果在获取验证码状态倒计时保存时长（单位：分钟）
		};
	},
	onShow() {
		let login_num = uni.getStorageSync('login_num'); //上次倒计时剩余秒数
		if (Number(login_num) > 0) {
			//有缓存的话
			let login_destroy_time = uni.getStorageSync('login_destroy_time'); //上次退出时间
			let login_get_code_num = uni.getStorageSync('login_get_code_num'); //上次剩余获取验证码次数
			let nowDate = new Date();
			let newDateStr = nowDate.valueOf(); //当前时间字符串
			let thisDate = new Date(login_destroy_time); // 缓存起来的时间
			let state = Number(login_destroy_time) > 0 && newDateStr - login_destroy_time < 60 * this.destroyMin * 1000;
			if (state) {
				this.num = login_num;
				this.getCode = true;
				this.setIntervalFun();
			}
			if (state || (thisDate.getFullYear() == nowDate.getFullYear() && thisDate.getMonth() == nowDate.getMonth() && thisDate.getDate() == nowDate.getDate())) {
				// 5分钟内或者同一天就认（剩余次数）
				this.getCodeNum = login_get_code_num;
			}
		}
	},
	methods: {
		getInput(e) {
			let { value } = e.detail;
			if (value != '') {
				if (value.charAt(0) != 1) {
					this.phone = 1;
					this.showToast('手机号开头是1');
				} else if (value.charAt(1) != '' && Number(value.charAt(1)) < 3) {
					this.phone = 1;
					this.showToast('手机号格式错误');
				} else {
					this.phone = value;
				}
			}
		},
		checkPhone(state = false) {
			// 用于界面UI
			let { phone, checkNum } = this;
			return REG.isPoneAvailable(phone) && (state || checkNum != '');
		},
		bindGetCode() {
			let { getCode, num, getCodeNum, phone } = this;
			if (!getCode) {
				if (phone == '') {
					uni.showToast({ title: '手机号不能为空', icon: 'none' });
				} else if (!REG.isPoneAvailable(phone)) {
					uni.showModal({
						title: '提示',
						content: '手机号输入不正确，请重新输入',
						showCancel: false,
						confirmText: '好的'
					});
				} else if (getCodeNum == 0) {
					uni.showToast({ title: '操作频繁！！！', icon: 'none' });
				} else if (getCodeNum >= 1) {
					this.getCode = true;
					API.getCode(phone).then(res => {
							app._log(res);
							if (res.code == 1) {
								this.showToast('发送成功');
								this.setIntervalFun();
								this.getCodeNum -= 1;
							} else {
								this.showToast(res.msg || '发送失败');
								this.getCode = false;
							}
						})
						.catch(err => {
							this.showToast(err.msg || '发送失败');
							this.getCode = false;
						});
				}
			}
		},
		setIntervalFun() {
			setInt = setInterval(() => {
				if (this.num == 1) {
					this.num = 60;
					clearInterval(setInt);
					this.getCode = false;
				} else {
					this.num -= 1;
				}
			}, 1000);
		},
		bindLoading() {
			let { phone, checkNum } = this;
			if (phone == '') {
				uni.showToast({ title: '手机号不能为空', icon: 'none' });
			} else if (!REG.isPoneAvailable(phone)) {
				uni.showModal({
					title: '提示',
					content: '手机号输入不正确，请重新输入',
					showCancel: false,
					confirmText: '好的'
				});
			} else {
				let obj = { mobile: phone, code: checkNum };
				if (uni.getStorageInfoSync('wxapp_openid') != null && uni.getStorageInfoSync('wxapp_openid') != undefined) {
					obj.wxapp_openid = uni.getStorageSync('wxapp_openid');
				}
				API.userLogin(obj).then(res => {
					app._log(res);
					if (res.code == 1) {
						uni.setStorageSync('app_token', res.data.token);
						if (obj.wxapp_openid) {
							uni.removeStorageSync('wxapp_openid');
						}
						this.showToast('登录成功,正在跳转...');
						app.globalData.LOGION = true;
						setTimeout(() => {
							this.pageTo('/pages/index/index');
						}, 1500);
					} else {
						this.showToast(res.msg);
					}
				});
			}
		}
	},
	beforeDestroy() {
		// 页面卸载事件
		let { getCode, num, getCodeNum } = this;
		if (getCode && num != 60) {
			//获取验证码中退出
			uni.setStorageSync('login_num', num); //保存倒计时剩余秒数
			uni.setStorageSync('login_destroy_time', new Date().valueOf()); //保存退出时间
			uni.setStorageSync('login_get_code_num', getCodeNum); //保存剩余获取验证码次数
		}
	}
};
</script>

<style lang="scss" scoped>
// @keyframes swing {20%{ transform: rotate(15deg);}40% { transform: rotate(-10deg);}60%{transform: rotate(5deg);}80%{transform: rotate(-5deg);}100%{transform: rotate(0deg);}}
.main {
	margin: 152rpx 48rpx 0;
	.input_view {
		height: 116rpx;
		line-height: 116rpx;
		border-bottom: 2rpx solid #f8f8f8;
		position: relative;
		display: flex;
		align-items: center;
		text {
			display: block;
			line-height: 116rpx;
			position: absolute;
			right: -30rpx;
			font-size: 28rpx;
			padding: 0 30rpx;
			&.active {
				color: #252748;
			}
			&:not(.active) {
				color: #8f8f9a;
			}
		}
	}
	.red {
		position: absolute;
		top: 414rpx;
		left: 292rpx;
		// animation: swing 1s;
	}
	.btn {
		width: 654rpx;
		text-align: center;
		line-height: 92rpx;
		font-size: 32rpx;
		border-radius: 24rpx;
		margin-top: 138rpx;
		&:not(.active) {
			color: #d1d2db;
			background-color: #f0f0f6;
		}
		&.active {
			color: #fff;
			background-image: linear-gradient(270deg, #7f4aff 0%, #ab7bff 100%);
		}
	}
}
</style>
